# coding: utf-8
import os
import subprocess
import re
import time
import wda
from collections import defaultdict


cmd_iproxy = "iproxy -u {device} {port_pc}:{port_device}"
cmd_wda_default = "xcodebuild {option} -project {xcodeproj} -scheme {scheme}"
option_showdest = "-showdestination"
option_test = "test {destination}"
param_destination = "-destination id={device}"
wda_device_port = 8100
local_url = "http://localhost:{port}"
WDA_BASE_PATH = '/Users/jiang/Data/autotest/testautomation/wda/wda2/WebDriverAgent/'


def deploy_proxy_wda(device, port_pc):
    return _get_wda_proxyclient(device, port_pc)


def deploy_usb_wda(device):
    return _get_wda_usbclient(device)


def run_iproxy(device, port_pc, port_device):
    """启动iproxy将pc本机port映射对应设备端口"""
    cmd = cmd_iproxy.format(
        device=device, port_pc=port_pc, port_device=port_device
    )
    p = subprocess.Popen(cmd, shell=True)
    return p


def _run_wda_test(device):
    """为设备启动wda test"""
    cmd = cmd_wda_default.format(
        option=option_test.format(destination=param_destination.format(
            device=device
        )),
        xcodeproj=WDA_BASE_PATH + 'WebDriverAgent.xcodeproj',
        scheme='WebDriverAgentRunner'
    )
    p = subprocess.Popen(cmd, shell=True)
    return p


def _get_wda_usbclient(device, timeout=120):
    """usb连接启动wda，推荐:少一个iproxy进程"""
    subprocess_list = []
    p = _run_wda_test(device)
    c = wda.USBClient(udid=device, port=wda_device_port)
    if c.wait_ready(timeout=timeout):
        subprocess_list.append(p)
    else:
        del c
        p.kill()
    return c, subprocess_list


def _get_wda_proxyclient(device, port_pc, timeout=100):
    """iproxy方式启动wda"""
    subprocess_list = []
    p = _run_wda_test(device)
    p_proxy = _run_iproxy(device, port_pc, wda_device_port)
    c = wda.Client(local_url.format(port=port_pc))
    if c.wait_ready(timeout=timeout):
        subprocess_list.append(p)
        subprocess_list.append(p_proxy)
    else:
        del c
        p.kill()
        p_proxy.kill()
    return c, subprocess_list


if __name__ == '__main__':

    device_list = [
        'dc04d7204f1ad7dcdfcef35c242d969831a859ff'
    ]
    print("init wda_util")

